"""
权限数据模式（Schema）定义
处理权限相关的请求与响应数据结构
"""
from typing import Optional, List
from datetime import datetime
from pydantic import BaseModel, Field, field_validator
import re


class PermissionBase(BaseModel):
    """权限基础数据模型"""
    name: str = Field(..., min_length=2, max_length=100, description="权限名称")
    slug: str = Field(..., min_length=2, max_length=100, description="权限标识")
    description: Optional[str] = Field(None, description="权限描述")
    module: str = Field(..., min_length=2, max_length=50, description="所属模块")
    action: str = Field(..., min_length=2, max_length=50, description="权限动作")
    
    @field_validator('slug')
    def validate_slug(cls, v):
        if not re.match(r'^[a-z0-9_.:]+$', v):
            raise ValueError('权限标识只能包含小写字母、数字、下划线、冒号和点')
        return v
    
    @field_validator('module')
    def validate_module(cls, v):
        if not re.match(r'^[a-z0-9_]+$', v):
            raise ValueError('模块名只能包含小写字母、数字和下划线')
        return v
    
    @field_validator('action')
    def validate_action(cls, v):
        if not re.match(r'^[a-z0-9_]+$', v):
            raise ValueError('动作名只能包含小写字母、数字和下划线')
        return v


class PermissionCreate(PermissionBase):
    """创建权限请求模型"""
    pass


class PermissionUpdate(BaseModel):
    """更新权限请求模型(部分更新)"""
    name: Optional[str] = Field(None, min_length=2, max_length=100)
    description: Optional[str] = None
    
    model_config = {"from_attributes": True}


class PermissionWholeUpdate(PermissionBase):
    """完整更新权限请求模型"""
    pass


class PermissionResponse(PermissionBase):
    """权限响应模型"""
    id: int
    created_at: datetime
    updated_at: datetime
    
    # 使用现代Pydantic v2配置风格
    model_config = {"from_attributes": True}


class PermissionListResponse(BaseModel):
    """权限列表响应模型"""
    items: List[PermissionResponse]
    total: int
    page: int
    page_size: int
    pages: int
